<template>
    <div>
        <!-- alt键 + 点击 跳转到文档页面 -->
        <el-card shadow="hover">
            <template #header>
                <el-button type="primary" class="el-icon-plus" @click="addShow">添加</el-button>
            </template>

            <el-table :data="tradeInfo" border>
                <el-table-column label="序号" type="index" width="80" align="center" />

                <el-table-column label="品牌名称" prop="tmName" />

                <el-table-column label="品牌LOGO">
                    <!-- 子组件无法决定自己的模式。需要用到插槽 -->
                    <template slot-scope="{ row }">
                        <el-image :src="row.logoUrl" style="width:100px;height: 60px;"></el-image>
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope='{row}'>
                        <el-button type="warning" size="small" class="el-icon-edit" @click="updateShow(row)">修改</el-button>
                        <el-button type="danger" size="small" class="el-icon-delete-solid"
                            @click="deleteTrademark(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!--
                分页器：
                current-page:当前第几页
                total:总页数
                page-size:每一页有多少条数据
                page-sizes:设置每一页有多少条数据
                layout:布局操作
             -->
            <el-pagination :current-page=page :total=total :page-size=limit :page-sizes="[3, 6, 9]"
                style="margin-top: 20px;text-align: center" layout="prev,pager,next,jumper,->,sizes,total"
                @current-change="getTradeInfo" @size-change="changeSize" />

            <!--添加或添加组件
                :visible.sync：对话框显示或者隐藏
                -->
            <el-dialog :title="TradeMarkfrom.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogHidden">

                <el-form label-width="140px" :model="TradeMarkfrom" :rules="rules" ref="ruleForm">
                    <el-form-item label="品牌名称" prop="tmName">
                        <el-input autocomplete="off" placeholder="请输入品牌名称" v-model="TradeMarkfrom.tmName" />
                    </el-form-item>

                    <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">

                        <!-- 收集数据不能用v-model
                        actions:图片上传地址(前面要加dev-api)
                        :on-success：图片上传成功后会执行一次
                        :before-upload 图片上传成功之前会执行一次
                        -->
                        <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload"
                            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="TradeMarkfrom.logoUrl" :src="TradeMarkfrom.logoUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>

                    </el-form-item>
                </el-form>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogHidden = false">取消</el-button>
                        <el-button type="primary" @click="AddorUpdateTradeMark">确定</el-button>
                    </span>
                </template>

            </el-dialog>


        </el-card>
    </div>
</template>

<script>
export default {
    name: 'Trademark',
    data() {
        return {
            tradeInfo: [],
            page: 1,
            limit: 3,
            total: 10,
            dialogHidden: false,
            //品牌的信息
            TradeMarkfrom: {
                tmName: '',
                logoUrl: ''
            },
            //表单验证
            rules: {
                tmName: [
                    /*  required:表示必填 
                        message:提示信息
                        trigger:触发时机
                        min:最少
                        max:最多
                    */
                    { required: true, message: '品牌名称不能为空', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度应在 2 到 8 个字符', trigger: 'change' }
                ],
                logoUrl: [
                    { required: true, message: '图片不得为空', trigger: 'change' }
                ],
            }
        }
    },
    mounted() {
        console.log(this.$API);
        this.getTradeInfo();
    },
    methods: {

        //获取列表数据，分页器点击事件
        async getTradeInfo(pages = 1) {
            this.page = pages
            const { page, limit } = this
            const result = await this.$API.trademark.reqTradeMark(page, limit);
            console.log(result);

            //如果成功
            if (result.code === 200) {
                //列表数据
                this.tradeInfo = result.data.records
                //总条数
                this.total = result.data.total
            }
        },

        //分页器size改变
        changeSize(limit) {
            this.limit = limit
            this.getTradeInfo()
        },

        //是否显示添加对话框，以及清除之前的数据
        addShow() {
            this.dialogHidden = true
            this.TradeMarkfrom = { tmName: '', logoUrl: '' }
        },

        //是否显示修改对话框
        updateShow(row) {
            this.dialogHidden = true
            //row就是当前这一列的信息
            this.TradeMarkfrom = { ...row }
        },

        //上传图片成功执行的
        handleAvatarSuccess(res, file) {
            //res:上传成功之后返回给前端的数据
            console.log(res);
            //file:上传成功之后服务器返回给前端的数据
            console.log(file);
            //收集了图片的数据,这样上传成功后就会带给服务器
            this.TradeMarkfrom.logoUrl = res.data
        },

        //上传图片之前执行的
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },

        //添加和修改品牌页面确定按钮的事件
        //表单验证通过之后才能点击
        AddorUpdateTradeMark() {
            this.$refs.ruleForm.validate(async (pass) => {
                //会返回一个布尔值,没通过表单验证则返回false,通过了返回true
                console.log(pass);

                if (pass) {
                    this.dialogHidden = false
                    //发送请求(tmName和logoUrl)
                    const result = await this.$API.trademark.reqAddorUpdateTradeMark(this.TradeMarkfrom)
                    //如果成功
                    if (result.code === 200) {
                        //三元表达式判断是否有id，有则是修改，无则是添加
                        this.$message({
                            type: 'success',
                            message: this.TradeMarkfrom.id ? '修改成功' : '添加成功'
                        });
                        //然后重新获取一遍列表数据，重新渲染
                        //同时三元表达式判断重新渲染后停留在哪一页
                        this.getTradeInfo(this.TradeMarkfrom.id ? this.page : 1)
                    }
                }
                else {
                    return false
                }

            })
        },

        //点击删除按钮
        deleteTrademark(row) {
            //敏感操作弹框
            this.$confirm('是否要删除该品牌', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                //点击确定后发送请求
                const result = await this.$API.trademark.reqDeleteTradeMark(row.id)
                if (result.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getTradeInfo(this.tradeInfo.length > 1 ? this.page : this.page - 1)
                }
            }).catch(() => {
                //点击取消
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
}
</script>

<style>  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
  }

  .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
  }

  .avatar {
      width: 178px;
      height: 178px;
      display: block;
  }
</style>